﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace BPMS.Core.Builders
{
    public abstract class BuilderBase
    {
        /// <summary>
        /// 实体对应表名
        /// </summary>
        public string DataRecordName { get; private set; }

        /// <summary>
        /// 实体对应数据字段集合
        /// </summary>
        public IEnumerable<DataFieldAttribute> DataFieldList { get; private set; }

        /// <summary>
        /// 实体类型
        /// </summary>
        public Type EntityType { get; private set; }

        public BuilderBase(Type entityType)
        {
            EntityType = entityType;
            this.DataRecordName = DataStructureCache.GetDataRecordName(EntityType);
            this.DataFieldList = DataStructureCache.GetDataFieldList(EntityType);
        }

        /// <summary>
        /// 属性集合
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        protected IEnumerable<PropertyInfo> PropertyList(Type type)
        {
            return DataStructureCache.GetPropertyList(type);
        }

        protected string GetConditionClause(object whereObject)
        {
            if (null == whereObject)
                return string.Empty;
            return string.Join(" AND ", PropertyList(whereObject.GetType()).Select(GetCondtionClauseItem));
        }

        protected string GetConditionClauseByKey()
        {
            return string.Join(" AND ", DataFieldList.Where(item => item.IsPrimaryKey).Select(GetCondtionClauseItem));
        }

        protected string GetDataColumnName(DataFieldAttribute dataField)
        {
            return "[" + dataField.FieldName + "]";
        }

        protected string GetDataParameterName(DataFieldAttribute dataField, string strPrefix = "")
        {
            return "@" + strPrefix + dataField.FieldName;
        }

        protected string GetCondtionClauseItem(PropertyInfo propertyInfo)
        {
            return "[" + propertyInfo.Name + "]=@" + propertyInfo.Name;
        }

        protected string GetCondtionClauseItem(DataFieldAttribute dataField)
        {
            return "[" + dataField.FieldName + "]=@" + dataField.FieldName;
        }

        public abstract string GetOperateStatement();

        public string GetOperateByKeyStatement()
        {
            return GetOperateStatement() + GetConditionClauseByKey();
        }

        public string GetOperateByConditionStringStatement(string whereClause)
        {
            return GetOperateStatement() + whereClause;
        }

        public string GetOperateByConditionObjectStatement(object whereObject)
        {
            return GetOperateStatement() + GetConditionClause(whereObject);
        }
    }
}
